package trungnt.wipeoff.model;

import trungnt.wipeoff.Cs;
import trungnt.wipeoff.PlayState;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;

public class GridActor extends Actor {

	private PlayState _playState;

	private ShapeRenderer shapeRenderer;

	public GridActor(PlayState playState) {
		this._playState = playState;

		this.shapeRenderer = new ShapeRenderer();
		this.shapeRenderer.setColor(Color.DARK_GRAY);

		this.setBounds(Cs.GRID_PADDING, 0, Cs.CELL_SIZE.x * Cs.GRID_COLUMN_CNT + (Cs.CELL_PADDING * Cs.GRID_COLUMN_CNT), Cs.CELL_SIZE.y
				* Cs.GRID_ROW_CNT + (Cs.CELL_PADDING * Cs.GRID_ROW_CNT));

		this.addListener(new InputListener() {
			@Override
			public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
				int col = (int) (x / (Cs.CELL_SIZE.x + Cs.CELL_PADDING));

				if (col < Cs.GRID_COLUMN_CNT) {
					Gdx.input.setInputProcessor(null);
					
					_playState.movingSampleNumber(col);
				}
			}

			@Override
			public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
				return true;
			}
		});
	}

	@Override
	public void draw(SpriteBatch batch, float parentAlpha) {
		batch.end();

		this.shapeRenderer.setProjectionMatrix(batch.getProjectionMatrix());
		this.shapeRenderer.begin(ShapeType.Line);
		for (int i = 0; i <= Cs.GRID_COLUMN_CNT; i++) {
			this.shapeRenderer.line(this.getX() + (Cs.CELL_PADDING * i) + (Cs.CELL_SIZE.x * i), this.getY(), this.getX() + (Cs.CELL_PADDING * i)
					+ (Cs.CELL_SIZE.x * i), this.getHeight());
		}

		for (int y = 0; y <= Cs.GRID_ROW_CNT; y++) {
			this.shapeRenderer.line(this.getX(), this.getY() + (Cs.CELL_PADDING * y) + (Cs.CELL_SIZE.y * y), this.getWidth() + Cs.GRID_PADDING, this
					.getY()
					+ (Cs.CELL_PADDING * y) + (Cs.CELL_SIZE.y * y));
		}
		this.shapeRenderer.end();

		batch.begin();
	}
}
